Skip to content

fix(relay): don't re-run an agent resume against a relay that never held the terminal (STA-5698) - #16989

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-5698-relay-age-gate-r1
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-5698-relay-age-gate-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​243 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​243
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​177 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172

What this fixes (ELI5)

Orca keeps a small helper process — the relay — running on your SSH host. It owns your remote terminals, and Orca reconnects to it when you come back.

When Orca reconnects and the relay answers "I don't have that terminal", Orca starts a fresh shell and replays whatever started the original terminal — the agent launch, the claude --resume … argv, the startup command. On a normal cold restore that is exactly right: your agent comes back.

But the relay can be replaced while you're away (an Orca upgrade, a host reboot, host-side cleanup). The replacement relay truthfully says "I don't have that terminal" — it never did. Meanwhile the old relay's shell may still be alive on the host as an orphan. Orca then replayed the resume, and you got a second agent running against the same worktree, fighting the first one over the same session state.

After this change, Orca checks how old the answering relay is before believing it. relay.status already reports the daemon's uptimeMs. A daemon that has only been up 5 minutes cannot have owned a binding created 2 hours ago — so its "it's absent" answer proves nothing about that process. In that case Orca:

  • still opens a terminal (you always get a shell — the spawn is never blocked),
  • does not replay launchAgent / the resume argv / command,
  • tells you, via the existing "resume unavailable" banner, so you decide what to run.

A plain shell is recoverable. A duplicate agent racing an orphan over one worktree is not.

Before / after

Before After
Cold restore, same relay still running Resume replays Unchanged — resume replays
Relay replaced, binding older than the daemon Resume replays → 2nd agent vs. live orphan Plain shell, resume dropped, banner shown
relay.status times out / rejects / errors Resume replays Unchanged — resume replays
relay.status answers, no uptimeMs (older host) Resume replays Unchanged — resume replays
Local / non-SSH provider (no host RPC) Resume replays Unchanged — resume replays

Verdict vocabulary

Per docs/reference/ssh-execution-boundary.md, the vocabulary stays exactly live / unverifiable / exited. This change narrows one specific case from exited to unverifiable: a positive absence answer from a daemon that provably never held the binding is not positive evidence about that process.

Silence is never promoted to a verdict. Every one of these leaves today's behavior byte-for-byte unchanged, by construction — each is an early return false:

  • provider has no requestHostRpc (optional call → undefined)
  • relay.status rejects, times out, or throws (catch → return false)
  • the reply is not an object
  • uptimeMs is absent, non-numeric, non-finite, or negative
  • no lease dates the binding (cold restore, older persisted state)
  • the answering relay is older than, equal to, or younger-only-inside-the-clock-slack

Only an answer that arrives and is demonstrably younger suppresses the resume.

On the clock comparison

uptimeMs is the host's own elapsed-time counter; binding age is the client's elapsed time since the lease's createdAt. Both are durations, so this compares two independently measured elapsed times — no clock-offset correction is possible or needed, and no wall-clock sync between client and host is assumed. A 30s slack (RELAY_AGE_CLOCK_SLACK_MS) absorbs jitter and the gap between daemon start and the first binding write.

Remote wire compatibility

Confirmed against docs/reference/remote-wire-compatibility.md: no wire change.

  • No new RPC request field; relay.status is called with {} exactly as skill-ssh-relay-client.ts already does.
  • No new response field — uptimeMs is already published at src/relay/relay-daemon.ts:131.
  • No new stream opcode.
  • agentResumeUnavailable already exists in the preload/renderer contract (src/preload/api/pty-api.ts:68) and is already produced by ipc/spawn-commit.ts for the Codex resume path. It is added to main's PtySpawnResult and rides the existing IPC response spread. The runtime spawn response builds an explicit field whitelist (id, incarnationId, stablePaneOwner, agentSessionEnsure), so the flag does not reach the remote wire.

An older host simply omits uptimeMs → no verdict → unchanged behavior.

Failing-first proof

Production reverted (git checkout the 4 modified files + rm the new module), new test file kept:

########## PRE-FIX (production reverted, new test kept) ##########
     × spawns a shell but drops a resume argv the replacement relay never held 6ms
     × drops launchAgent rather than starting a second agent over the same worktree 1ms
     × drops a startup command 0ms
 Test Files  1 failed (1)
      Tests  3 failed | 7 passed (10)

########## POST-FIX ##########
 Test Files  1 passed (1)
      Tests  10 passed (10)

(The suite has since grown to 12 tests with two added coverage cases; the three suppression tests are the ones that can fail pre-fix.)

Honest note on the other tests. The task asked that every new test fail pre-fix. Only the three suppression tests can: the remaining nine pin "behavior is unchanged" (older relay, rejection, missing uptimeMs, non-object reply, no lease, no host RPC, no startup intent, sub-slack gap, spawn never gated). A test asserting that today's behavior is preserved cannot fail before the change — that is what it means. Their value is proven by the ablation table below instead: each goes red when the gate is made too permissive. I have not claimed failing-first for them.

Ablation table

Each production hunk reverted individually against the 12-test suite:

# Hunk Result
H1 record relay-positive absence (onRelayPositiveAbsence) RED — 3 failed / 8 passed
H2 fallback branch call in spawnForStablePane RED — 3 failed / 8 passed
H3 carriesStartupIntent guard RED — 1 failed / 10 passed
H4 answeringRelayPredatesBinding guard RED — 6 failed / 5 passed
H5 stripStartupIntent RED — 2 failed / 9 passed
H6 agentResumeUnavailable flag RED — 3 failed / 8 passed
H7 undatable-binding guard (age === null) RED — 1 failed / 10 passed
H8 uptimeMs type guard RED — 1 failed / 10 passed
H9 relay.status failure catch RED — 1 failed / 10 passed
H10 non-object status guard (true deletion) RED — 2 failed / 10 passed
H11 clock slack RED — 1 failed / 10 passed
H12 lease createdAt lookup RED — 3 failed / 8 passed
H13 ipc agent_started gate GREEN — UNCOVERED
H14 ipc markClaudePtySpawned gate GREEN — UNCOVERED
H15 runtime agent_started / claude-marker gates GREEN — UNCOVERED

H13–H15 are uncovered and I am saying so rather than papering over it. They are three one-line consequential gates: a suppressed resume produced a plain shell, so agent_started telemetry and the Claude-launch marker must not fire for an agent that never started. Without them this change would introduce a false agent_started. Covering them needs a full setupPtyIpcSuite run with a registered SSH provider, a lease store, and a relay-absence rejection driven through executePtyIpcSpawn — disproportionate to three one-line conditions, so I left them uncovered rather than write a test that only restates the condition.

Note on H10: my first mutation (status = status ?? {}) left the suite green because it re-introduced a null guard. True deletion is red. Reporting both because the weak mutation is the kind that makes an ablation table lie.

Gates

  • pnpm tc — exit 0
  • oxlint (incl. --type-aware and react-doctor configs) on all changed files — clean, no max-lines disable added (the fallback body was extracted into the new module to stay under 300)
  • npx oxfmt --write <changed paths> only — never pnpm format
  • git diff --check — clean
  • pnpm test src/main/ipc/pty — 10 pre-existing failures on both the clean tree and this branch (identical set, in pty-spawn-env-agent-overlays, pty-login-shell-startup-commands, pty-serializer-settlement-mapping, pty-spawn-env-codex-home-routing); this branch adds 12 passing tests (594 → 606 passing)

What I did NOT verify

  • No live SSH relay-replacement reproduction. I did not stand up a real SSH host, kill and replace its relay daemon with an orphaned shell surviving, and observe the banner. All evidence here is unit-level against spawnForStablePane.
  • No Electron/CDP run. I did not render the resume-unavailable banner in the running app for this branch. I reused the existing agentResumeUnavailable → showSessionRestoredBanner('resume-unavailable') path rather than adding a new surface, but I did not visually confirm it end to end.
  • H13–H15 have no test (above).
  • Runtime/paired-host path surfaces nothing to the user. The suppression itself applies on both the IPC and runtime spawn paths (both go through spawnForStablePane). The banner only reaches the renderer on the IPC path, because the runtime spawn response is an explicit whitelist and adding the field there would be a wire change this ticket forbids. A paired-runtime user gets the plain shell without the banner.
  • Lease createdAt and recycled PTY ids. upsertSshRemotePtyLease preserves the oldest createdAt when a relay recycles a pty-N id (see the STA-3077 note in ssh-pty-lease-operations.ts). That biases binding age older, i.e. toward suppression. I judged that acceptable — the conservative direction here is a plain shell — but I did not measure how often it fires in practice.
  • No perf measurement of the added relay.status round-trip. It is bounded at 2s and only runs on the absence fallback when startup intent is present, but I did not time it against a real relay.

Relationship to the other STA-5698 PRs

This is a different approach from the two open siblings, and deliberately narrower:

uptimeMs is strictly weaker evidence than a minted identity (it cannot distinguish two daemons that both predate the binding), but it works against every existing host with no negotiation, including hosts that will never ship an identity field. These are alternatives, not stackable; whichever lands, the others should close. Flagging this rather than assuming — the merge choice is yours.

Closes STA-5698.

…eld the terminal

When a stable pane's reattach fails with positive absence, the fallback re-spawns
using the original request's spawn options, replaying `launchAgent` / resume argv /
`command`. On a cold restore that is right. After a relay daemon replacement it is
not: the binding may name a PTY from a previous daemon whose shell is still alive as
an orphan, so the replay starts a SECOND agent against the same worktree.

`relay.status` already reports `uptimeMs`. A daemon whose uptime is shorter than the
age of the binding it just answered about demonstrably never owned that binding, so
its positive absence is `unverifiable`, not `exited`. On that verdict the fallback
still spawns a shell — the spawn is never gated — but drops the startup intent and
sets the existing `agentResumeUnavailable` flag so the pane shows the
resume-unavailable banner instead of claiming the old session came back.

Loss of contact produces no verdict: a missing host RPC, a rejected or timed-out
`relay.status`, a non-object reply, an absent or unusable `uptimeMs`, and a binding
nothing can date all leave today's behavior exactly as-is.

Client-side policy only — no new wire field and no new stream opcode.

STA-5698
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change detects when an SSH PTY relay was replaced by comparing relay uptime with the persisted binding age. When confirmed, stable-pane fallback removes startup intent and marks the spawn with agentResumeUnavailable. Spawn commit paths use this flag to skip Claude PTY registration and agent_started telemetry. Tests cover suppression, replay, invalid relay status, missing lease data, clock slack, and absent host RPC.

Merge Risk: 🟡 Moderate · up to 24614

When a replacement relay is detected, the change creates a plain shell instead of replaying agent startup, but the current implementation can first mark the existing SSH PTY as exited and the runtime path does not return the resume-unavailable indication. This can misclassify a live terminal and leave some users without the expected recovery message, so follow-up is needed before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 41.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 12 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: preventing agent resume replay when an SSH relay never held the terminal. It is specific and concise.
Description check ✅ Passed The description is detailed, on-topic, and covers the problem, implementation, rationale, linked issue, behavior changes, testing, limitations, compatibility, and review risks. It does not reproduce e…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is detailed, on-topic, and covers the problem, implementation, rationale, linked issue, behavior changes, testing, limitations, compatibility, and review risks. It does not reproduce every template heading or checklist item, but the required substantive information is mostly present.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 68b383b2-5d16-4631-927c-8740617972c6

📥 Commits

Reviewing files that changed from the base of the PR and between c4b3929 and 24614bd.

📒 Files selected for processing (6)
  • src/main/ipc/pty/ipc/spawn-commit.ts
  • src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
  • src/main/ipc/pty/pane/stable-owner.ts
  • src/main/ipc/pty/pane/stable-pane-relay-age-resume-suppression.test.ts
  • src/main/ipc/pty/runtime/spawn-commit.ts
  • src/main/providers/pty-spawn-result.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment on lines +249 to +251
if (isSshPtyAbsentFromRelayError(error)) {
args.onRelayPositiveAbsence?.()
}

@coderabbitai coderabbitai Bot Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- applicable repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print
printf '%s\n' '--- SSH execution boundary ---'
cat -n docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner outline ---'
ast-grep outline src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- changed path and direct flow ---'
sed -n '220,325p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- onPtyExit definitions and callers ---'
rg -n -A8 -B8 'onPtyExit|isSshPtyAbsentFromRelayError|spawnForStablePane|attachStablePaneOwner' src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- convention file headers ---'
find /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4 -type f -name '*.md' -print0 |
  while IFS= read -r -d '' f; do
    printf '\n### %s\n' "$f"
    head -5 "$f"
  done
printf '%s\n' '--- SSH execution boundary ---'
sed -n '1,220p' docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner imports and flow ---'
sed -n '1,90p' src/main/ipc/pty/pane/stable-owner.ts
sed -n '220,325p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- focused definitions ---'
rg -n -A35 -B12 'class OrcaRuntimeService|onPtyExit\s*\(' src
printf '%s\n' '--- focused diff ---'
git diff -- src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- stable-owner tests ---'
find src/main -type f \( -name '*stable-owner*.test.ts' -o -name '*pty*persisted*repair*.test.ts' \) -print

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- knowledge files ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -type f -name '*.md' -print
printf '%s\n' '--- SSH boundary terms ---'
rg -n -A4 -B4 'loss of contact|unverifiable|live|exited|relay' docs/reference/ssh-execution-boundary.md
printf '%s\n' '--- stable-owner exact source ---'
rg -n 'isSshPtyAbsentFromRelayError|onPtyExit|spawnForStablePane|attachStablePaneOwner|relay|unverif' src/main/ipc/pty/pane/stable-owner.ts
sed -n '1,80p' src/main/ipc/pty/pane/stable-owner.ts
sed -n '220,320p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- runtime implementation location ---'
rg -l 'class OrcaRuntimeService' src/main
rg -n -A45 -B10 '^[[:space:]]*onPtyExit[[:space:]]*\(' src/main/runtime
printf '%s\n' '--- focused diff ---'
git diff --stat -- src/main/ipc/pty/pane/stable-owner.ts
git diff -U20 -- src/main/ipc/pty/pane/stable-owner.ts

Repository: stablyai/orca

Length of output: 24421


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- attachStablePaneOwner complete flow ---'
sed -n '185,285p' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- onPtyExit complete decision flow ---'
sed -n '15960,16090p' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- liveness verdict implementation ---'
rg -n -A30 -B8 'getPtyLivenessVerdict|markPtyLivenessUnverifiable|SSH_EXIT_UNCONFIRMED_REASON' src/main/runtime/orca-runtime.ts
printf '%s\n' '--- relay absence error contract and provider path ---'
rg -n -A20 -B10 'isSshPtyAbsentFromRelayError|SshPtyAbsent|ABSENT_FROM_RELAY|absent from relay' src/main
printf '%s\n' '--- focused persisted-repair cases ---'
rg -n -A18 -B18 'owner_unverified|replacement relay|young|onPtyExit.*not|positive absence|relay' src/main/ipc/pty-persisted-incarnation-repair.test.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- replacement-relay suppression implementation ---'
cat -n src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
printf '%s\n' '--- all relay age/replacement symbols ---'
rg -n -A12 -B12 'relayAge|relay age|replacement relay|relay replacement|replayed intent|spawnWithoutReplayedIntent|grace|young' src/main src/relay
printf '%s\n' '--- SSH provider lifecycle and relay identity ---'
sed -n '200,275p' src/main/providers/ssh-pty-session-reattach.ts
sed -n '1,130p' src/main/providers/ssh-pty-errors.ts
rg -n -A18 -B18 'restart|reconnect|generation|relay.*start|startedAt|createdAt|age' src/main/ssh src/main/providers src/relay | head -300
printf '%s\n' '--- relevant conventions and learnings ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src.md
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings/src-main-pty.md

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- suppression helper ---'
wc -l src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
cat -n src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts
printf '%s\n' '--- stable pane spawn context and all age-related fields ---'
rg -n -A12 -B12 'StablePaneSpawnContext|relayAnsweredAbsent|spawnWithoutReplayedIntent|age|generation|replacement' src/main/ipc/pty/pane src/main/providers/ssh-pty-session-reattach.ts
printf '%s\n' '--- reattach error path ---'
sed -n '215,265p' src/main/providers/ssh-pty-session-reattach.ts
printf '%s\n' '--- focused persisted-repair tests ---'
sed -n '330,510p' src/main/ipc/pty-persisted-incarnation-repair.test.ts
printf '%s\n' '--- focused relay-absence tests ---'
sed -n '1,110p' src/main/providers/ssh-pty-relay-absence-verdict.test.ts

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- focused relay-absence test file ---'
wc -l src/main/ipc/pty/pane/stable-pane-relay-absence-respawn.test.ts
cat -n src/main/ipc/pty/pane/stable-pane-relay-absence-respawn.test.ts
printf '%s\n' '--- stable-owner context declaration ---'
rg -n -A35 -B8 'type StablePaneSpawnContext|interface StablePaneSpawnContext|onRelayPositiveAbsence' src/main/ipc/pty/pane/stable-owner.ts
printf '%s\n' '--- exact exit surface effects ---'
sed -n '16080,16180p' src/main/runtime/orca-runtime.ts

Repository: stablyai/orca

Length of output: 18101


Classify young replacement relays as unverifiable before exit handling. attachStablePaneOwner calls runtime.onPtyExit(..., 0, ...) before spawnWithoutReplayedIntent checks relay.status.uptimeMs. This treats a possibly live SSH PTY as exited. Add a test that asserts onPtyExit is not called.

Source: Coding guidelines

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Judged this from the code rather than the label, and I think it's real as a contract gap — but it is pre-existing, not introduced here, and the fix is bigger than the thread implies. Leaving it open for @brennanb2025 rather than resolving.

The ordering claim is accurate. At head 24614bd:

  • stable-owner.ts:249-251 — the new hook only records relayAnsweredAbsent.
  • stable-owner.ts:262 — runtime?.onPtyExit(owner.ptyId, 0, owner.incarnationId) fires immediately after, inside the same catch.
  • stable-owner.ts:305-307 — spawnWithoutReplayedIntent (and therefore answeringRelayPredatesBinding → relay.status.uptimeMs) runs only after attachStablePaneOwner has already returned null.

So the exit is published before anything has evaluated whether the answering relay could have owned the binding.

Why the exit code matters, and it isn't cosmetic. In orca-runtime.ts:

  • :15992 preservesAbnormalSshSurface requires exitCode < 0. The call site passes 0, so it is false.
  • :16002 is therefore skipped — markPtyLivenessUnverifiable(ptyId, SSH_EXIT_UNCONFIRMED_REASON) never runs.
  • :16012 processDeathCertified = exitCode >= 0 || … is true, so reconcileAgentStatusForEndedProcessFn runs and the agent status is reconciled as ended.

onPtyExit(ptyId, 0, …) is a certified clean death. That is exited.

Which is the one verdict this case is not allowed to be. docs/reference/ssh-execution-boundary.md, "Distinguishing unverifiable from exited": "A stale event, an event for a superseded incarnation, or one quiet terminal with no host evidence does not [establish exited]." A relay whose uptime is shorter than the binding's age is a superseded incarnation by construction — that is the PR's own premise, stated verbatim at relay-replacement-resume-suppression.ts:76-83 ("its positive absence is unverifiable rather than exited"). The code acts on that premise for the resume intent and not for the liveness verdict.

Two things the thread gets wrong, though.

  1. It isn't a regression from this PR. :262 is unchanged on main and fires for every isPtyAlreadyGoneError. This PR adds the knowledge that a subset of those absences is unverifiable; it does not make the verdict worse than it already was.

  2. "Add a test that asserts onPtyExit is not called" is not the right assertion, and the naive fix regresses something else. Skipping onPtyExit leaves the runtime holding a binding no relay will ever answer for. And unconditionally passing exitCode < 0 for every SshPtyAbsentFromRelayError would mark genuinely-exited SSH PTYs unverifiable, which feeds verifyUnstoppedPtys (unstopped-pty-verification.ts:17) and can block worktree removal. The correct shape is: still retire the surface, but choose exitCode 0 vs -1 based on the age probe — which means hoisting answeringRelayPredatesBinding above :262 and awaiting up to RELAY_AGE_STATUS_TIMEOUT_MS (2s) inside the teardown path. That is a real latency and design change, and it is why the "heavy lift" tag is the accurate part of this comment.

One thing worth acting on regardless of the above: every case in stable-pane-relay-age-resume-suppression.test.ts passes runtime: undefined (:63, :217), so runtime?.onPtyExit is a no-op in all 12 tests. Whatever this PR decides the verdict should be, nothing currently pins it.

Also unrelated to this thread but in the same file — answeringRelayPredatesBinding is named backwards. It returns true when age > uptimeMs + slack, i.e. when the relay started after the binding and therefore does not predate it. The behavior is correct and the test names use "predates" in the correct English sense (…test.ts:138 pairs "predates the binding" with olderRelay and expects a replay), so the identifier is the sole outlier. Worth renaming before someone inverts the gate reading it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@.wk-scratch/reply-16989-a.md

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

if [ -f .wk-scratch/reply-16989-a.md ]; then
  cat .wk-scratch/reply-16989-a.md
else
  printf '%s\n' 'Referenced draft does not exist in this checkout.'
  fd -a '^reply-16989-a\.md$' . || true
fi

Length of output: 415


@brennanb2025, .wk-scratch/reply-16989-a.md is not present in this checkout. Please paste the draft content or provide an accessible file path.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This describes #16989's tree only. Nothing here survives the PR's closure — and main's onPtyExit(…, 0, …) is correct as written. Recording the check so it is not rediscovered.

The reported ordering does not exist on main. At origin/main (94e7586665) stable-owner.ts is 293 lines, the exit is at :255, and spawnWithoutReplayedIntent / relay.status.uptimeMs appear nowhere in the repo — grep -rn answeringRelayPredatesBinding src/ returns zero hits. The "publishes before the gate" relationship is created by this PR, so it dies with it.

The ordering is real inside the PR. attachStablePaneOwner publishes the exit and then return nulls; the gate runs one frame later, in spawnForStablePane. So the PR suppresses the replayed startup intent but never retracts the exit it already published. Two aggravators, also PR-local: kill.ts:79-88 publishes -1 for the identical isPtyAlreadyGoneError predicate, and adopt-stable.ts:60 calls attachStablePaneOwner directly, so that caller never reaches the gate at all.

On main the 0 is not a coercion — it is a host-verified absence. By the time line 255 runs, the two non-evidence classes have already been diverted above it:

if (error instanceof TerminalSessionOwnerUnverifiedError) {   // :235
  throw new Error('terminal_pane_owner_unverified')
}
if (isDaemonEndpointGoneError(error)) {                        // :239
  throw new TerminalHostGoneError()
}
if (!isPtyAlreadyGoneError(error)) {                           // :242
  throw error
}

Each remaining arm of isPtyAlreadyGoneError (provider/liveness.ts:58-67) is positive evidence from the owning host on this path:

  • SshPtyAbsentFromRelayError — raised only at ssh-pty-session-reattach.ts:238, after :229 diverts identity mismatch ("the id names a LIVE PTY owned by another pane"). Pinned both directions by ssh-pty-relay-absence-verdict.test.ts.
  • /PTY ".+" not found/i — produced only by src/relay/pty-handler.ts, i.e. the relay answering. On the attach path it is converted to the class above before any caller sees it; the other four throw sites are closeStartupQueryAuthority, sendSignal, getCwd, getInitialCwd, none of which are on this path.
  • /Session not found/i — SessionNotFoundError, reachable here only from a received daemon response (decodeDaemonResponseError) or from resolution.kind === 'absent' in DaemonSessionOwnerResolver.spawnAttachOnly, which routes kind === 'unknown' to TerminalSessionOwnerUnverifiedError instead.

A transport failure cannot reach line 255: stable-pane-relay-absence-respawn.test.ts:98-107 pins that a lost link, a request timeout, and a bare SSH_SESSION_EXPIRED all rethrow and keep the binding.

So the downstream composition is right. resolveUnreportedExitCause(0) yields { kind: 'unknown', reason: 'cause_unreported' } — "the reporting host did not say why", which is exactly what a relay-confirmed absence with no status tells us. processDeathCertified (orca-runtime.ts:16012) becomes true, correct for a verified absence, and preservesAbnormalSshSurface (:15992) correctly does not mark the pane unverifiable. Switching main to -1 would be the regression, not the fix: it would publish stop_unverified and markPtyLivenessUnverifiable for a process the host positively reported gone.

Leaving this thread open per the reviewer's request. No main PR was opened, because there is nothing on main to change.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@brennanb2025, agreed on the scope correction.

onPtyExit(..., 0, ...) is correct on main. On main, the attach path has only host-verified absence cases at that point. The replacement-relay age gate does not exist there.

The finding is limited to #16989. This PR adds a new fact that can change the absence verdict: a relay younger than the binding could not have owned that binding. The current flow publishes the certified exit before it evaluates that fact.

No main follow-up is needed. The open thread should remain scoped to the PR-local ordering and its direct callers, including adopt-stable.ts.

🐇🔍


✏️ Learnings added
Learnt from: brennanb2025
Repo: stablyai/orca PR: 16989
File: src/main/ipc/pty/pane/stable-owner.ts:249-251
Timestamp: 2026-08-28T14:53:40.394Z
Learning: In the Orca stable-pane attach path on main, `runtime.onPtyExit(ptyId, 0, incarnationId)` follows host-verified PTY absence and is correct. PR `#16989` adds replacement-relay age detection after `attachStablePaneOwner` returns; when the answering SSH relay is younger than the persisted binding, that PR-local ordering can publish a certified exit before the new relay-age evidence classifies the absence as unverifiable. Any fix must be scoped to the PR behavior, not main.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

Comment on lines +228 to +232
if (ctx.isClaudeLaunch && !ctx.stablePaneOwner && !ctx.result.agentResumeUnavailable) {
markClaudePtySpawned(ctx.result.id)
}
if (args.telemetry && !ctx.stablePaneOwner) {
// Why: a suppressed resume produced a plain shell, so there is no agent launch to report.
if (args.telemetry && !ctx.stablePaneOwner && !ctx.result.agentResumeUnavailable) {

@coderabbitai coderabbitai Bot Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Return agentResumeUnavailable from the runtime response. The response whitelist at Line 288 omits the flag, while the reservation result at Line 302 retains it. The initial runtime caller cannot show the resume-unavailable banner.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real, and this is the gap @brennanb2025 already flagged in the PR description — the paired/runtime path gets the suppression but not the surfacing. Two corrections though: the stated fix is incomplete, and the reason it hasn't been done is not a wire constraint.

The omission is real. At head 24614bd:

  • runtime/spawn-commit.ts:288-301 builds response as an explicit whitelist; agentResumeUnavailable is not in it.
  • :302-310 resolvePaneSpawnReservation spreads ...ctx.result, so the reservation path does carry it. That asymmetry is exactly as described.
  • By contrast ipc/spawn-commit.ts:196-217 builds its response with ...ctx.result (a spread), which is why the renderer banner works on the IPC path at all — ipc-pty-connect-result.ts:36,52 → apply-reattach-payload.ts:281 / fresh-spawn-start.ts:212.

But adding it at Line 288 alone does nothing. There is a second whitelist downstream: runtime/spawn.ts:20-34 toRuntimeSpawnReply re-projects the result into {id, incarnationId, wslDistro, stablePaneOwner, agentSessionEnsure} and is applied at :84, :88, :95 and :98. A field added at :288 is dropped one frame later. Both have to change or the fix is dead code with a passing-looking test.

And it still wouldn't reach a user. ptyController.spawn (runtime/controller.ts:43) is consumed by OrcaRuntimeService.createTerminal (orca-runtime.ts:28975), whose result type is RuntimeTerminalCreate (shared/runtime-terminal-contracts.ts:245-258). That type has no such field either, and its consumers are the CLI / automation / mobile terminal create surface — there is no banner there to show. So the honest fix is four layers, not one: spawn-commit.ts:288 → toRuntimeSpawnReply → RuntimeTerminalCreate (plus shared/runtime-client-export-parity.test.ts:136) → createTerminal. "Quick win" is the wrong tag.

On the wire question — the stated blocker doesn't hold. docs/reference/remote-wire-compatibility.md Rule 1 is explicit: "a new optional JSON field on an existing frame is safe … Every JSON payload is parsed with a decoder that ignores unknown keys." An optional agentResumeUnavailable?: true on the terminal create result is Rule 1, not Rule 2 — Rule 2 is about stream opcodes, which decoders drop silently, and none is involved here. The Rule 1 caveat also holds cleanly in this direction: a new client against an old host sees the field absent and shows no banner, which is precisely today's behavior, so absence degrades to the status quo rather than to a wrong claim. This is not a reason to leave it out.

Why it's more than "Minor". Without it, orca terminal create with a resume/--agent against an SSH worktree can return success while main has deliberately dropped the startup intent, and the caller has no way to tell. That is the ssh-execution-boundary.md anti-pattern — "an operation … that reports success may not have run — check the durable state it should have changed rather than trusting the return" — applied to Orca's own API rather than to a shell command.

Cheapest correct shape: RuntimeTerminalCreate already carries warning?: string (runtime-terminal-contracts.ts:255), which the CLI already surfaces. Populating that on a suppressed resume gets the information to the automation caller with no new field at all — while a dedicated optional boolean is still available and still Rule 1-safe if a machine-readable signal is wanted.

Leaving open — this needs a scope call from @brennanb2025, not a resolve.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@.wk-scratch/reply-16989-b.md

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

fd -H -a '^reply-16989-b\.md$' . -x sh -c 'echo "===== $1 ====="; cat "$1"' sh {}

Length of output: 251


@brennanb2025, the search completed with no matches. The referenced file is not present in this checkout. Please paste the reply content so I can evaluate the scope decision.

You are interacting with an AI system.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This describes #16989's tree only, and the omission it names is a deliberate main decision. Nothing here survives the PR's closure. Recording the check so it is not rediscovered.

There is no agentResumeUnavailable on the runtime path to return. main does produce the flag — but only on the IPC path (src/main/ipc/pty/ipc/spawn-commit.ts:213-215, from ctx.codexResumeLaunch.notifyResumeUnavailable), surfaced through preload/api/pty-api.ts:70. The runtime controller has no producer, and runtime/spawn-preflight.ts:129-131 says so in as many words:

// Why: the drop still applies here, but this controller's result has no field for
// notifyResumeUnavailable — runtime/relay panes start fresh without the notice.

So on main the whitelist drops nothing. Only this PR gives the runtime path a value to drop.

The one-line fix would be dead code even inside the PR. runtime/spawn.ts:20-33 toRuntimeSpawnReply is a second whitelist, between commitRuntimePtySpawn and the caller:

return {
  id: result.id,
  ...(result.incarnationId ? { incarnationId: result.incarnationId } : {}),
  ...(typeof result.wslDistro === 'string' ? { wslDistro: result.wslDistro } : {}),
  ...(result.stablePaneOwner ? { stablePaneOwner: result.stablePaneOwner } : {}),
  ...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {})
}

Adding the field to the response object alone would surface no banner anywhere.

The PR's stated reason for not doing it does not hold, though. The description calls adding the field to the runtime response "a wire change this ticket forbids". Per docs/reference/remote-wire-compatibility.md Rule 1, "a new optional JSON field on an existing frame is safe" — decoders .strip() unknown keys, and an older peer simply does not read it. The correct objection is not wire risk; it is that both whitelists would need the field and the runtime path has no producer for it.

What is left on main is a product gap, not a defect. A paired-runtime or mobile pane whose Codex resume falls back to a fresh session gets no "resume unavailable" notice — by the documented design quoted above. Worth a ticket if that matters. It is not a coercion bug, and it is not this PR's.

Leaving this thread open per the reviewer's request. No main PR was opened.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

ast-grep outline src/main/ipc/pty/runtime/spawn.ts --items all
ast-grep outline src/main/ipc/pty/runtime/spawn-preflight.ts --items all
ast-grep outline src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts --items all
ast-grep outline src/main/ipc/pty/pane/stable-owner.ts --items all

printf '\n=== Runtime reply projection ===\n'
rg -n -A35 -B5 'function toRuntimeSpawnReply|const toRuntimeSpawnReply|toRuntimeSpawnReply\s*=' \
  src/main/ipc/pty/runtime/spawn.ts

printf '\n=== Runtime preflight notice contract ===\n'
rg -n -A12 -B8 'notifyResumeUnavailable|agentResumeUnavailable' \
  src/main/ipc/pty/runtime/spawn-preflight.ts

printf '\n=== PR suppression producer ===\n'
rg -n -A18 -B12 'spawnWithoutReplayedIntent|agentResumeUnavailable' \
  src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts \
  src/main/ipc/pty/pane/stable-owner.ts

printf '\n=== Commit response projection ===\n'
rg -n -A35 -B5 'const response = \{' src/main/ipc/pty/runtime/spawn-commit.ts

Length of output: 17441


@brennanb2025, the main clarification is correct. The existing runtime Codex-resume behavior does not produce agentResumeUnavailable. The spawn-preflight.ts comment documents that decision.

This PR changes the condition. spawnWithoutReplayedIntent returns agentResumeUnavailable: true at Line 144, and spawnForStablePane returns that result to the runtime flow at Lines 305-309.

Therefore, the PR-specific omission remains valid. commitRuntimePtySpawn drops the produced flag at Lines 288-301. toRuntimeSpawnReply drops it again at Lines 20-33. Adding the field only at Line 288 would not expose it to the runtime caller.

I agree that this is not a wire-compatibility blocker. I also agree that the correct fix requires both runtime response projections, plus the contract and consumer work needed to present a warning. The original “Quick win” scope was incorrect.

🐇 🔎


✏️ Learnings added
Learnt from: brennanb2025
Repo: stablyai/orca PR: 16989
File: src/main/ipc/pty/runtime/spawn-commit.ts:228-232
Timestamp: 2026-08-28T14:54:12.837Z
Learning: In `src/main/ipc/pty/runtime/spawn-preflight.ts`, the existing runtime Codex-resume drop behavior deliberately has no `notifyResumeUnavailable` result field. In PR `#16989`, `src/main/ipc/pty/pane/relay-replacement-resume-suppression.ts` separately produces `PtySpawnResult.agentResumeUnavailable` for confirmed replacement SSH relays. Any runtime caller notification for that PR-specific flag must propagate through both `src/main/ipc/pty/runtime/spawn-commit.ts` and `src/main/ipc/pty/runtime/spawn.ts` response whitelists.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

You are interacting with an AI system.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

STA-5698: three-way comparison of #16989, #16839, #16901

Read the diffs rather than the titles. Verdicts below are from the code and from git diff --name-only set intersections, not from the PR descriptions.


At a glance

#16989 (this PR) #16839 #16901
Size +420/−5, 6 files +1151/−140, 40 files +251/−142, 13 files (2 prod)
Layer client policy only (src/main/ipc/pty/**) relay and client (relay stamp → lease → client policy) relay only (src/relay/pty-handler.ts)
Mechanism infer replacement from relay.status.uptimeMs vs lease createdAt prove ownership by matching a relay-minted relayProcessId prevent id reuse by minting pty2:<epoch>:<n>
Wire none Rule 1 additive optional fields Rule 3 content change
Mergeable ✅ 21 pass ⚠️ CONFLICTING (50 pass, but pre-conflict) ✅ 29 pass

#16989 — client-side age gate

relay-replacement-resume-suppression.ts:87-123. On a relay-positive absence, read relay.status.uptimeMs, compare against the SSH lease's createdAt, and if age > uptimeMs + 30_000 strip command / launchAgent / startupIngress / agentSessionEnsure from the fallback spawn. The spawn itself is never gated (:139-144); only the replayed intent is.

Wire: none. uptimeMs is already published; no new field, no opcode.

Fixes uniquely: it is the only one of the three that needs no host-side change, so it protects users whose relay is already deployed and will not be restarted. It is also the only one whose suppression reaches the telemetry and Claude-spawn bookkeeping (ipc/spawn-commit.ts:133,183, runtime/spawn-commit.ts:228,232), so a suppressed resume no longer emits agent_started.

Fails to fix: the orphan itself; the pty-N collision class; and — decisive — it cannot tell a relay restart from a host reboot. After a reboot uptimeMs is small and createdAt is old, so the gate fires and the user loses their resume in the one case where nothing could possibly have survived.

Blast radius / reversibility: smallest of the three. One new module, four guard clauses, no persisted state, no wire surface. A clean git revert restores prior behavior with nothing left behind. Lowest risk to land, lowest cost to undo.


#16839 — relay process identity

The relay mints a process identity at startup and publishes it on relay.status (and, only when the client sets a new optional requestRelayProcessId, on spawn/attach results). The client persists it on the lease (shared/ssh-types.ts:214 SshRemotePtyLease.relayProcessId) and ssh-relay-absence-verdict.ts:11-30 returns exited only on an exact match — everything else is unverifiable.

Wire: additive optional fields, so Rule 1 by construction — but it lands squarely on Rule 1's own caveat: "The field is safe only for as long as every reader treats it as optional. The moment a newer client requires it, that client is broken against every host that predates the field." This client requires it: resolveSshRelayAbsenceVerdict:14-16 returns unverifiable when bindingRelayProcessId is absent. The PR body accepts this explicitly — "An older host simply omits the identity, so the client classifies its positive absence as unverifiable." Concretely: every user who updates the desktop app but has not restarted their relay loses agent resume on every SSH pane, until the host is upgraded. That is a much larger population than "users whose relay was replaced".

Fixes uniquely: it is the only one with a positive proof of ownership rather than an inference — a same-relay absence stays exited and resume keeps working, which neither of the others can assert. It is also the only one that strips ORCA_AGENT_LAUNCH_TOKEN from the fallback env (stable-pane-spawn-fallback.ts:20-23); #16989's stripStartupIntent leaves the env untouched, so a suppressed spawn there still carries the launch token.

Fails to fix: the orphan itself, the id-collision class, and — same as #16989 — the reboot case: a rebooted host runs a new relay with a new identity, so the match fails and the resume is suppressed even though nothing survived.

Blast radius / reversibility: largest by a wide margin. 40 files across relay, providers, IPC, runtime, and shared types, plus a new persisted lease field. It is CONFLICTING with main today, so its 50 green checks describe a tree that no longer exists and must be re-run after a rebase. Reverting after release leaves persisted relayProcessId values behind (harmless, ignored) but the review cost is front-loaded and unavoidable.


#16901 — relay incarnation in the id

Two production lines: pty-handler.ts:456-464 takes a ptyIdMintEpoch (default randomUUID()), and :1589 mints pty2:${encodeURIComponent(epoch)}:${n} instead of pty-${n}. Everything else in the diff is test churn.

Wire: Rule 3 — the host changes the content it publishes with no codec change. I checked the decoder: shared/ssh-pty-id.ts:23-43 splits on the first @@ and treats relayPtyId as an opaque remainder, so ssh:conn@@pty2:E:1 round-trips through parseAppSshPtyId / toRelaySshPtyId unchanged, and the embedded colons are unambiguous. Nothing rejects the new shape. The skew cost is real but self-limiting: a binding minted by an old relay stops matching once that relay upgrades, so each stale binding takes one absence-fallback at the upgrade boundary and is correct forever after.

Fixes uniquely: it is the only one of the three that removes the id-reuse class — a reset relay minting pty-2 that a durable client binding then attaches to, landing on the wrong live process. Neither other PR touches that. It also retires the compensating machinery: attachIdentityMismatches (pty-handler.ts:398-400, whose own comment names this exact collision and which is permissive when identity is absent) becomes redundant.

Fails to fix: it suppresses nothing. A replacement relay still answers "absent" for pty2:E1:3, the #16763 fallback still fires, and the resume is still replayed. #16901 removes the misattach failure, not the duplicate resume failure. It is not a fix for STA-5698's reported harm on its own.

Blast radius / reversibility: 2 production lines, but they change every remote PTY id, which is persisted in leases and bindings. A revert after users accumulate pty2: bindings makes those bindings unmatchable by the reverted relay — recoverable (each becomes one absence-fallback) but not free. Medium.

(Small note in passing: pty-handler.ts:2309 still parses /^pty-(\d+)$/ on the revive path to advance nextId. After this change it never matches, so nextId no longer advances on revive. It's currently harmless — a new process gets a new epoch, and the mint loop guards this.ptys / pendingReviveIds — but it is now dead code whose safety depends on the epoch never being made stable across restarts. Worth deleting or commenting.)


Are any two complementary? — Yes, and this is measurable

I took git diff --name-only <merge-base> <head> for each PR and intersected the sets:

#16989 ∩ #16901  →  (empty)
#16989 ∩ #16839  →  src/main/ipc/pty/ipc/spawn-commit.ts
                    src/main/ipc/pty/pane/stable-owner.ts
                    src/main/ipc/pty/runtime/spawn-commit.ts
                    src/main/providers/pty-spawn-result.ts
#16901 ∩ #16839  →  src/relay/pty-handler.ts
                    src/relay/pty-handler-test-harness.ts
                    src/relay/pty-handler-spawn-admission.test.ts
                    src/relay/subprocess.test.ts

#16989 and #16901 share zero files and zero mechanism. One is a client policy on src/main/ipc/pty/**; the other is host-side id minting in src/relay/. They fix different failures — duplicate resume vs. misattach — and neither's correctness depends on the other's absence. This is the #16985 / #16980 pattern exactly: same ticket, looked like duplicates, turned out to be disjoint. The mutual-exclusivity claim in this PR's description is refuted for that pair and should be retracted.

They are in fact synergistic, which is the more interesting result. Once ids carry the relay incarnation, the client can read the epoch out of the binding it already holds and compare it against the answering relay's current epoch. That is a proof of replacement, with no relay.status round-trip, no uptimeMs, and no 30-second clock slack — it strictly dominates the heuristic in answeringRelayPredatesBinding. #16901 is the substrate that would let this PR's gate stop guessing.

#16989 and #16839 are genuinely mutually exclusive — four shared files, and both rewrite the same decision point in stable-owner.ts. Pick one.

#16901 and #16839 are redundant at the relay layer — both encode relay incarnation identity, one intrinsically in the id and one as a side-channel field, and they collide in pty-handler.ts. Landing both means maintaining two identity mechanisms for one concept.


Recommendation

Land #16901. Do not land #16839. Hold #16989 pending the argument below.

#16901 is the only one of the three that removes a failure class rather than detecting it, it is two production lines, its wire skew is self-healing, and it is disjoint from this PR. #16839 buys a strictly better signal than #16989 at ~2.7× the diff, 40 files, an unresolved conflict with main, and a regression that hits every user on a not-yet-upgraded relay — the cost is not proportionate to the gain over #16901 + a small client gate.

If duplicate-resume suppression is still wanted after #16894 and #16895 land, build it on #16901's epoch comparison rather than on either uptime or a side-channel identity field.

The strongest argument against #16989

It revives an approach that was already tried and closed for this exact defect, one day earlier, by its own author.

#16843 — "fix(ssh): stop the absence fallback resuming an agent a replaced relay never held (STA-5698)" — was closed on 2026-08-27 with this rationale:

this PR detected a possible orphan by inference (relay uptime vs. the lease's last attach). Review blocked it because an age comparison convicts any younger relay, including after a host reboot where no orphan can exist, so every SSH pane on that host silently loses its agent resume.

answeringRelayPredatesBinding is that same age comparison — age > uptimeMs + RELAY_AGE_CLOCK_SLACK_MS, with the lease's createdAt substituted for its lastAttachedAt and a 30-second slack added. Neither substitution addresses the objection: after a reboot, uptimeMs is small and createdAt is old, the gate fires, and the resume is suppressed in the one scenario where an orphan is impossible. Relay restarts overwhelmingly come from reboots and upgrades, so the false-positive case is plausibly the common case.

The same closing note also records that the harm could not be reproduced on Linux at all:

it reproduced the precondition exactly — positive absence, a demonstrably younger daemon — but kill -9 on the relay closed the pty master, the kernel delivered SIGHUP, and the shell and agent were gone in 0.3s. No orphan to collide with.

and that the surviving Windows case has a host-side cause and a host-side fix (assignCurrentProcessToJob, #16895) rather than a client-side detection problem. If that investigation still stands, #16989 pays a real cost — losing resume after every reboot — to defend against an orphan that does not occur on Linux and is being removed at the source on Windows.

The honest counter is that #16989 is cheap and trivially revertible, and that #16894 / #16895 are still open. But that argues for landing those two, not for re-landing the inference this PR's author already rejected.

Reviewed at #16989 24614bd, #16839 96b413b, #16901 7eda0e0, against main 8fa1b3c.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Coordinator note: this PR uses the approach you already rejected in #16843

I dispatched this PR from STA-5698's written "Suggested direction" without first checking whether a
prior attempt existed. One did. #16843 was closed on 2026-08-27 for precisely this mechanism, and
the closing comment is decisive:

this PR detected a possible orphan by inference (relay uptime vs. the lease's last attach). Review
blocked it because an age comparison convicts any younger relay, including after a host reboot
where no orphan can exist, so every SSH pane on that host silently loses its agent resume.

That objection applies to this PR unchanged. The reboot case is not hypothetical: after any host
reboot the relay is always younger than the binding, there is never an orphan, and every SSH pane on
that host would silently lose its agent resume.

#16843 also recorded why client-side detection was abandoned in general:

Every guard considered — uptime, daemon nonce, host boot id, an inherited-fd liveness token —
fails open in some cases and fails closed in others … Preventing the orphan is cheaper and certain.

And a live repro could not produce the harm on Linux at all: kill -9 on the relay closed the pty
master, the kernel delivered SIGHUP, and shell and agent were gone in 0.3s — no orphan to collide
with. The harm was only real on Windows, and for a different reason.

The sanctioned fixes already exist as open PRs, both green and both unreviewed:

Those are prevention on the host, which is what #16843 concluded to do.

What is still worth keeping here

Two things, and I would not want them lost with the PR:

  1. The renderer half — spawn the shell, decline the resume, show the banner — is the correct
    outcome if a guard is ever justified. fix(ssh): stop the absence fallback resuming an agent a replaced relay never held (STA-5698) #16843 said so explicitly.
  2. Review of this PR surfaced a separate, real, pre-existing defect that is not about the age
    gate at all: stable-owner.ts:262 fires onPtyExit(..., 0, ...) before the age probe at
    :305-307, so orca-runtime.ts certifies a clean exited for an absence that this PR's own helper
    classifies as unverifiable. That is the same "failure becomes fact" coercion this batch has been
    clearing everywhere else, and it exists on main today. It deserves its own PR regardless of what
    happens to this one.

Also noted: answeringRelayPredatesBinding is named backwards relative to what it returns.

Recommendation: close this in favour of #16894 + #16895, and split the stable-owner.ts:262
coercion out as its own change. Not closing anything myself — that call is yours.

@OrcaWin

OrcaWin commented Oct 11, 2026 •

Copy link
Copy Markdown
Collaborator

SSH still works: Orca connects to the host over SSH and routes workspace operations through the managed remote Orca server (orcad). These merges remove the legacy SSH relay, not SSH support.

Closing as obsolete after the merged SSH relay retirement in #27214 and #27215. This PR concerns the SSH relay PTY attach, recovery, replay, or lease lifecycle. #27214 removed the desktop relay connection/fallback path; #27215 deleted the SSH relay server, deployment assets, and relay-only tests. SSH hosts now use the managed Orca server (orcad), and unsupported hosts fail explicitly, so this relay-specific work is no longer planned. This closes the proposed relay implementation; it does not claim that any independent local, WSL, or managed-server behavior was fixed.

@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Thanks @brennanb2025 — the relay itself is gone, but the idea behind this (don't auto-resume an agent when the host's "terminal not found" was never observed as a real exit) still applies to managed hosts and paired runtimes. I've captured it on #13716 with credit to this PR; this one stays closed since its mechanism was relay-specific.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants